<template>
  <view class="search-page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <text class="search-icon">🔍</text>
        <input
          class="search-input"
          type="text"
          v-model="searchQuery"
          placeholder="搜索商品或商家"
          focus
          confirm-type="search"
          @input="onSearchInput"
          @confirm="handleSearch"
        />
        <text class="clear-icon" v-if="searchQuery" @click="clearSearch">✕</text>
      </view>
      <view class="search-btn" @click="handleSearch">搜索</view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>
    
    <!-- 搜索内容区域 -->
    <scroll-view class="search-content" scroll-y>
      <!-- 加载中提示 -->
      <view class="loading-tip" v-if="loading">
        <text class="loading-icon">⏳</text>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 搜索历史 -->
      <view class="search-section" v-if="!searchQuery && !loading && searchHistory.length > 0">
        <view class="section-header">
          <text class="section-title">搜索历史</text>
          <text class="clear-history" @click="clearHistory">清空</text>
        </view>
        <view class="history-tags">
          <view 
            class="history-tag" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @click="selectHistory(item)"
          >
            <text class="history-icon">🕒</text>
            <text class="history-text">{{ item }}</text>
          </view>
        </view>
      </view>
      
      <!-- 热门搜索 -->
      <view class="search-section" v-if="!searchQuery && !loading">
        <view class="section-header">
          <text class="section-title">热门搜索</text>
          <text class="hot-icon">🔥</text>
        </view>
        <view class="hot-tags">
          <view 
            class="hot-tag" 
            v-for="(item, index) in hotSearches" 
            :key="index"
            :class="{ 'top-three': index < 3 }"
            @click="selectHotSearch(item)"
          >
            <text class="rank-number">{{ index + 1 }}</text>
            <text class="hot-text">{{ item }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载中 -->
      <view class="loading-container" v-if="loading">
        <text class="loading-text">⏳ 搜索中...</text>
      </view>
      
      <!-- 搜索结果 -->
      <view class="search-results" v-else-if="searchQuery">
        <!-- 无结果 -->
        <view class="empty-result" v-if="isEmpty">
          <text class="empty-icon">🔍</text>
          <text class="empty-text">未找到"{{ searchQuery }}"相关内容</text>
          <text class="empty-tip">试试搜索其他关键词吧</text>
        </view>
        
        <!-- 有结果 -->
        <view class="result-list" v-else>
          <view class="result-tabs">
            <view 
              class="result-tab" 
              :class="{ 'active': resultTab === 'food' }"
              @click="resultTab = 'food'"
            >
              <text class="tab-text">商品</text>
              <text class="tab-count">({{ foodResults.length }})</text>
            </view>
            <view 
              class="result-tab" 
              :class="{ 'active': resultTab === 'merchant' }"
              @click="resultTab = 'merchant'"
            >
              <text class="tab-text">商家</text>
              <text class="tab-count">({{ merchantResults.length }})</text>
            </view>
          </view>
          
          <!-- 商品结果 -->
          <view v-if="resultTab === 'food'">
            <view 
              class="food-result-item" 
              v-for="(item, index) in foodResults" 
              :key="index"
              @click="goToFoodDetail(item)"
            >
              <image :src="item.image" mode="aspectFill" class="food-img" />
              <view class="food-info">
                <text class="food-name">{{ item.name }}</text>
                <text class="food-merchant">{{ item.merchantName }}</text>
                <view class="food-bottom">
                  <view class="price-row">
                    <text class="price">¥{{ item.price }}</text>
                    <text class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</text>
                  </view>
                  <text class="sold-count">已售{{ item.sold }}件</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 商家结果 -->
          <view v-if="resultTab === 'merchant'">
            <view 
              class="merchant-result-item" 
              v-for="(item, index) in merchantResults" 
              :key="index"
              @click="goToMerchant(item)"
            >
              <image :src="item.logo || '/static/default-merchant.jpg'" mode="aspectFill" class="merchant-logo" />
              <view class="merchant-info">
                <view class="merchant-name-row">
                  <text class="merchant-name">{{ item.name }}</text>
                  <view class="merchant-status" :class="{ 'closed': item.status !== 1 }">
                    <text class="status-text">{{ item.status === 1 ? '营业中' : '休息中' }}</text>
                  </view>
                </view>
                <text class="merchant-rating">⭐ {{ item.rating }} | {{ item.ratingCount }}评价</text>
                <text class="merchant-delivery">起送¥{{ item.minOrderAmount }} | 配送¥{{ item.deliveryFee }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      searchQuery: '',
      searchHistory: [],
      hotSearches: [
        '野生大翘嘴',
        '卵泡排骨',
        '宫保鸡丁',
        '红烧肉',
        '清蒸鲈鱼',
        '麻辣香锅',
        '拼单优惠',
        '新店特惠'
      ],
      resultTab: 'food', // 'food' or 'merchant'
      loading: false,
      // ⭐ API搜索结果
      searchResult: {
        foods: [],
        merchants: [],
        totalFoods: 0,
        totalMerchants: 0,
        currentPage: 0,
        pageSize: 20
      },
      // 实时搜索防抖定时器
      searchTimer: null
    }
  },
  computed: {
    // ⭐ 商品搜索结果
    foodResults() {
      return this.searchResult.foods || []
    },
    
    // ⭐ 商家搜索结果
    merchantResults() {
      return this.searchResult.merchants || []
    },
    
    // 是否为空结果
    isEmpty() {
      return this.searchQuery.trim() && 
             this.foodResults.length === 0 && 
             this.merchantResults.length === 0 &&
             !this.loading
    },
    
    // 是否还有更多数据
    hasMore() {
      if (this.resultTab === 'food') {
        return this.foodResults.length < this.searchResult.totalFoods
      } else {
        return this.merchantResults.length < this.searchResult.totalMerchants
      }
    }
  },
  onLoad() {
    this.getStatusBarHeight()
    this.loadSearchHistory()
  },
  onUnload() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  },
  methods: {
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      
      // H5环境下设置CSS变量
      // #ifdef H5
      if (typeof document !== 'undefined') {
        document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
      }
      // #endif
    },

    
    // 加载搜索历史
    loadSearchHistory() {
      try {
        const history = uni.getStorageSync('search_history') || []
        this.searchHistory = history.slice(0, 10) // 最多显示10条
      } catch (e) {
        this.searchHistory = []
      }
    },
    
    // 保存搜索历史
    saveSearchHistory(keyword) {
      if (!keyword.trim()) return
      
      let history = [...this.searchHistory]
      // 移除重复项
      history = history.filter(item => item !== keyword)
      // 添加到最前面
      history.unshift(keyword)
      // 最多保存10条
      history = history.slice(0, 10)
      
      this.searchHistory = history
      uni.setStorageSync('search_history', history)
    },
    
    // 清空搜索历史
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = []
            uni.removeStorageSync('search_history')
            uni.showToast({
              title: '已清空',
              icon: 'success',
              duration: 1500
            })
          }
        }
      })
    },
    
    // 搜索输入（带防抖的实时搜索）
    onSearchInput(e) {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      // 如果输入为空，清空搜索结果
      if (!this.searchQuery.trim()) {
        this.searchResult = {
          foods: [],
          merchants: [],
          totalFoods: 0,
          totalMerchants: 0,
          currentPage: 0,
          pageSize: 20
        }
        return
      }
      
      // 300ms 后自动搜索（防抖）- 输入即搜索
      this.searchTimer = setTimeout(() => {
        this.handleSearch()
      }, 300)
    },
    
    // ⭐ 执行搜索（调用后端API）
    async handleSearch() {
      const keyword = this.searchQuery.trim()
      
      if (!keyword) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 保存搜索历史
      this.saveSearchHistory(keyword)
      
      // 重置页码
      this.searchResult.currentPage = 1
      this.loading = true
      
      try {
        const res = await uni.request({
          url: 'http://localhost:8080/api/v1/search',
          method: 'GET',
          data: {
            keyword: keyword,
            type: 'all',  // 搜索全部
            page: 1,
            pageSize: 20
          }
        })
        
        if (res.statusCode === 200 && res.data.code === 200) {
          this.searchResult = res.data.data
          
          // 如果没有结果，显示提示
          if (this.foodResults.length === 0 && this.merchantResults.length === 0) {
            uni.showToast({
              title: '未找到相关结果',
              icon: 'none',
              duration: 2000
            })
          } else {
            // 显示搜索结果提示
            const totalResults = this.foodResults.length + this.merchantResults.length
            uni.showToast({
              title: `找到${totalResults}个结果`,
              icon: 'success',
              duration: 1500
            })
          }
        } else {
          uni.showToast({
            title: res.data.message || '搜索失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },
    
    // 清除搜索
    clearSearch() {
      this.searchQuery = ''
    },
    
    // 选择历史记录
    selectHistory(keyword) {
      this.searchQuery = keyword
      this.handleSearch()
    },
    
    // 选择热门搜索
    selectHotSearch(keyword) {
      this.searchQuery = keyword
      this.handleSearch()
    },
    
    // 跳转到商品详情
    goToFoodDetail(item) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${item.id}` +
             `&storeName=${encodeURIComponent(item.storeName)}` +
             `&name=${encodeURIComponent(item.name)}` +
             `&price=${encodeURIComponent(item.price)}` +
             `&originalPrice=${encodeURIComponent(item.originalPrice || '')}` +
             `&image=${encodeURIComponent(item.image)}`
      })
    },
    
    // 跳转到商家页面
    goToMerchant(item) {
      uni.navigateTo({
        url: `/pages/merchant-menu/merchant-menu?merchantId=${item.id}&merchantName=${encodeURIComponent(item.name)}`
      })
    },
    
    // 返回
    goBack() {
      const pages = getCurrentPages()
      // 如果只有当前页面（说明是直接访问或刷新的），跳转到首页
      if (pages.length <= 1) {
        uni.reLaunch({
          url: '/pages/home/home'
        })
      } else {
        // 否则返回上一页
        uni.navigateBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
:root {
  --status-bar-height: 20px;
}

.search-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.status-bar {
  background: #fff;
}

/* 加载中 */
.loading-container {
  padding: 100rpx 0;
  text-align: center;
  
  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 搜索头部 */
.search-header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  z-index: 999;
  
  .search-input-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 24rpx;
    
    .search-icon {
      font-size: 32rpx;
      margin-right: 12rpx;
      opacity: 0.6;
    }
    
    .search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .clear-icon {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #999;
      background: #e0e0e0;
      border-radius: 50%;
      margin-left: 12rpx;
      cursor: pointer;
      
      &:active {
        background: #d0d0d0;
      }
    }
  }
  
  .search-btn {
    padding: 0 20rpx;
    height: 60rpx;
    line-height: 60rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 28rpx;
    font-weight: 600;
    border-radius: 30rpx;
    cursor: pointer;
    white-space: nowrap;
    transition: all 0.3s ease;
    
    &:active {
      opacity: 0.8;
      transform: scale(0.95);
    }
  }
  
  .cancel-btn {
    font-size: 28rpx;
    color: #999;
    padding: 0 10rpx;
    cursor: pointer;
    white-space: nowrap;
    
    &:active {
      color: #667eea;
    }
  }
}

/* 搜索内容区域 */
.search-content {
  max-height: calc(100vh - var(--status-bar-height, 20px) - 112rpx);
  padding: 30rpx;
}

/* 加载中提示 */
.loading-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  
  .loading-icon {
    font-size: 80rpx;
    margin-bottom: 24rpx;
    animation: rotate 1.5s linear infinite;
  }
  
  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 搜索区块 */
.search-section {
  margin-bottom: 40rpx;
  
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;
    
    .section-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
    }
    
    .clear-history {
      font-size: 26rpx;
      color: #999;
      cursor: pointer;
      
      &:active {
        color: #667eea;
      }
    }
    
    .hot-icon {
      font-size: 28rpx;
    }
  }
}

/* 历史标签 */
.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .history-tag {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 16rpx 24rpx;
    background: #fff;
    border-radius: 40rpx;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:active {
      background: #f0f0f0;
      transform: scale(0.95);
    }
    
    .history-icon {
      font-size: 24rpx;
      opacity: 0.6;
    }
    
    .history-text {
      font-size: 26rpx;
      color: #666;
    }
  }
}

/* 热门标签 */
.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .hot-tag {
    display: flex;
    align-items: center;
    gap: 10rpx;
    padding: 16rpx 24rpx;
    background: #fff;
    border-radius: 40rpx;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.95);
    }
    
    &.top-three {
      background: linear-gradient(135deg, #fff5f5 0%, #ffe5e5 100%);
      
      .rank-number {
        color: #ff4757;
        font-weight: 700;
      }
      
      .hot-text {
        color: #ff4757;
        font-weight: 600;
      }
    }
    
    .rank-number {
      min-width: 32rpx;
      text-align: center;
      font-size: 24rpx;
      color: #999;
      font-weight: 600;
    }
    
    .hot-text {
      font-size: 26rpx;
      color: #666;
    }
  }
}

/* 空结果 */
.empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
  
  .empty-icon {
    font-size: 120rpx;
    opacity: 0.3;
    margin-bottom: 24rpx;
  }
  
  .empty-text {
    font-size: 30rpx;
    color: #666;
    margin-bottom: 12rpx;
  }
  
  .empty-tip {
    font-size: 26rpx;
    color: #999;
  }
}

/* 搜索结果 */
.result-list {
  .result-tabs {
    display: flex;
    align-items: center;
    gap: 40rpx;
    padding: 20rpx 0;
    margin-bottom: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .result-tab {
      display: flex;
      align-items: baseline;
      gap: 8rpx;
      padding-bottom: 16rpx;
      cursor: pointer;
      position: relative;
      
      .tab-text {
        font-size: 30rpx;
        color: #999;
        font-weight: 500;
        transition: all 0.3s ease;
      }
      
      .tab-count {
        font-size: 24rpx;
        color: #ccc;
        transition: all 0.3s ease;
      }
      
      &.active {
        .tab-text {
          color: #667eea;
          font-weight: 700;
          font-size: 32rpx;
        }
        
        .tab-count {
          color: #667eea;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 4rpx;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 2rpx;
        }
      }
    }
  }
}

/* 商品结果项 */
.food-result-item {
  display: flex;
  padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.15);
  }
  
  .food-img {
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
    background: #f0f0f0;
    margin-right: 24rpx;
  }
  
  .food-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .food-name {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .food-merchant {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 12rpx;
    }
    
    .food-bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .price-row {
        display: flex;
        align-items: baseline;
        gap: 12rpx;
        
        .price {
          font-size: 32rpx;
          font-weight: 700;
          color: #ff4757;
        }
        
        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
      }
      
      .sold-count {
        font-size: 22rpx;
        color: #999;
      }
    }
  }
}

/* 商家结果项 */
.merchant-result-item {
  display: flex;
  padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.15);
  }
  
  .merchant-logo {
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
    background: #f0f0f0;
    margin-right: 24rpx;
  }
  
  .merchant-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .merchant-name-row {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 8rpx;
      
      .merchant-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }
      
      .merchant-status {
        padding: 4rpx 12rpx;
        background: #e8f5e9;
        border-radius: 8rpx;
        
        .status-text {
          font-size: 20rpx;
          color: #4caf50;
          font-weight: 500;
        }
        
        &.closed {
          background: #ffebee;
          
          .status-text {
            color: #f44336;
          }
        }
      }
    }
    
    .merchant-rating {
      font-size: 24rpx;
      color: #ffa726;
      margin-bottom: 8rpx;
    }
    
    .merchant-delivery {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style>

